package On_class.L0331.book;

import java.io.*;

public class BooksDaoIO implements BooksDao {
        String file="books.txt";

    @Override
    public void insert(Books books) {
        Books b =select(books.getId());
        if (b==null){
            String s=books.getId()+"-"+books.getName()+"-"+books.getPrice()+"-"+books.getNumber()+"-"+books.getPrice();
            BufferedWriter bw=null;
            try {
                bw=new BufferedWriter(new FileWriter(file,true));
                bw.write(s);
                bw.newLine();
                bw.flush();
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                if(bw!=null){
                    try {
                        bw.close();
                    }catch (IOException e){
                        e.printStackTrace();
                    }

                }
            }
        }
    }

    @Override
    public void selectAll() {
        BufferedReader br=null;
        try {
            br=new BufferedReader(new FileReader(file));
            String line;
            while ((line=br.readLine())!=null){
                System.out.println(line);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(br!=null){
                try {
                    br.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }

        }
    }

    @Override
    public Books select(int id) {
        BufferedReader br=null;
        try {
            br=new BufferedReader(new FileReader(file));
            String line;
            while ((line=br.readLine())!=null){
                String[] s=line.split("-");
                int ids=Integer.parseInt(s[3]);
                if (id==ids){
                    double price=Double.parseDouble(s[2]);
                    int number=Integer.parseInt(s[3]);
                    Books books=new Books(id,s[1],price,number,s[4]);
                    return books;

                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (br!=null){
                try {
                    br.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    @Override
    public void update(int id, Books b) {

    }

    @Override
    public void delete(int id) {

    }
}
